<script setup lang="ts">
import { ref } from 'vue'
import type { patientAddReq } from '@/types/user'
import { patientAdd, patientDel, patientUpdate } from '@/api/user'
import { watch } from 'vue'
import {
  showFailToast,
  type FieldRule,
  type FormInstance,
  showSuccessToast,
  showConfirmDialog
} from 'vant'
const emits = defineEmits<{
  (e: 'getData'): void
}>()

const mode = ref<'add' | 'edit'>('add')
const show = ref(false)
const options = [
  {
    label: '男',
    value: 1
  },
  {
    label: '女',
    value: 0
  }
]
const form = ref<patientAddReq>({
  name: '',
  idCard: '',
  defaultFlag: 0,
  gender: 0
})

const rules: {
  name: FieldRule[]
  idCard: FieldRule[]
  //   gender: FieldRule[]
} = {
  name: [
    { required: true, message: '必填', trigger: 'onChange' },
    {
      pattern: /^.{2,32}$/,
      message: '请正确输入姓名',
      trigger: 'onChange'
    }
  ],
  idCard: [
    { required: true, message: '必填', trigger: 'onChange' },
    {
      pattern:
        /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/,
      message: '请正确输入身份证号',
      trigger: 'onChange'
    }
  ]
}

const defaultVal = ref(false)
// watch:侦听某些值的变化
/*
  const stop=watch(
   需要侦听的数据  / []  /()=>需要侦听的数据.某属性名
   ()=>{},
   {
    deep:true/false,
    immediate:true/false,
    flush:
         pre:渲染前执行回调
         post:渲染后执行回调
         sync:修改一次执行一次回调（渲染前）
   }
  )
*/
watch(defaultVal, newVal => {
  form.value.defaultFlag = newVal ? 1 : 0
})
const formCom = ref<FormInstance>()
// 新增与编辑
const save = async () => {
  formCom.value?.validate()
  const val = +form.value.idCard.slice(-2, -1) % 2
  if (val !== form.value.gender) {
    return showFailToast('身份证号与性别不符')
  }
  // 调用接口
  // 新增
  if (mode.value === 'add') {
    await patientAdd(form.value)
    showSuccessToast('添加患者成功')
  } else if (mode.value === 'edit') {
    const { defaultFlag, gender, id, idCard, name } = form.value
    await patientUpdate({ defaultFlag, gender, id, idCard, name })
    showSuccessToast('编辑患者成功')
  }
  show.value = false
  emits('getData')
}
// 每次关闭都清空表单数据与验证
const close = () => {
  form.value = {
    name: '',
    idCard: '',
    defaultFlag: 0,
    gender: 0
  }
  defaultVal.value = false
  setTimeout(() => {
    formCom.value?.resetValidation()
  }, 100)
}
// 删除事件
const delEvent = async () => {
  // 1：弹出确定框
  // 2:定义删除api
  // 3:导入与调用
  // 4：删除成功  a:提示  b:关闭弹框  c:清空数据与验证  d:刷新父级列表
  await showConfirmDialog({
    title: '温馨提示',
    message: '您确定删除该项吗？'
  })
  await patientDel(form.value.id!)
  showSuccessToast('删除成功')
  show.value = false
  emits('getData')
}

defineExpose({
  show,
  form,
  mode,
  defaultVal
})
</script>

<template>
  <div class="add-page">
    <van-popup
      @close="close"
      v-model:show="show"
      position="right"
      style="width: 100%; height: 100%"
    >
      <CpNavBar
        :back="() => (show = false)"
        :title="{ add: '添加患者', edit: '编辑患者' }[mode]"
        right-text="保存"
        @click-right="save"
      ></CpNavBar>
      <van-form class="form" ref="formCom">
        <van-field
          :rules="rules.name"
          v-model="form.name"
          label="真实姓名"
          placeholder="请输入真实姓名"
        ></van-field>
        <van-field
          :rules="rules.idCard"
          v-model="form.idCard"
          label="身份证号"
          placeholder="请输入身份证号"
        ></van-field>
        <!-- <van-field label="性别" :model-value="form.gender" :rules="rules.gender"> -->
        <van-field label="性别">
          <template #input>
            <CpRadioBtn :options="options" v-model="form.gender"></CpRadioBtn>
          </template>
        </van-field>
        <van-field label="默认就诊人">
          <template #input>
            <van-checkbox v-model="defaultVal"></van-checkbox>
          </template>
        </van-field>
      </van-form>
      <van-action-bar v-if="mode === 'edit'">
        <van-action-bar-button @click="delEvent">删除</van-action-bar-button>
      </van-action-bar>
    </van-popup>
  </div>
</template>

<style lang="scss" scoped>
.form {
  margin-top: 46px;
}
:deep() {
  .van-button__text {
    color: red;
  }
}
</style>
